package com.study.zk.lock.simple;

import com.study.zk.lock.zookeeper.ZookeeperDistributedLock;

import java.util.concurrent.locks.Lock;

/**
 * todo 当前还处在自己的方法里new的分布式锁，还不能在线程外让大家共用同一个对象；因为锁还需要完善。
 * todo 完善点：确保多线程下大家抢的是同一把锁。
 *
 * @author: chenhs
 * @date: Created in 10:58 2020/2/4
 **/
public class OrderServiceImplWithDisLock implements OrderService {

    /**
     * 此处static模拟了---将订单生成器独立成一个tomcat服务（场景）
     */
    private static OrderCodeGenerator ocg = new OrderCodeGenerator();


    @Override
    public void createOrder() {
        String orderCode;
        //分布式锁
        //Lock lock = new ZkDistributeLock("/study666");
        //Lock lock = new ZkDistributeImproveLock("/study666");
        Lock lock = new ZookeeperDistributedLock();
        try {
            lock.lock();
            //获取订单号
            orderCode = ocg.getOrderCode();
        } finally {
            lock.unlock();
        }

        System.out.println(Thread.currentThread().getName() + "================>" + orderCode);
        //...业务代码，此处省略100行代码
    }
}
